package me.key.iwifimanager2;

import android.annotation.SuppressLint;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;

import me.key.iwifimanager2.util.Global;

@SuppressLint("HandlerLeak")
public class SocketThread extends Thread {
	private OutputStream outputStream = null;
	private InputStream inputStream = null;
	private Socket socket;
	private SocketAddress socketAddress;
	public static Handler socketHandler;
	private boolean key = true;
	private RxThread rxThread;
	private Handler mainHandler;
	private String ip;
	private int port;
	
	public SocketThread(Handler mainHandler,String ip,int port) {
		super();
		this.mainHandler = mainHandler;
		this.ip = ip;
		this.port = port;
	}
	void connect() {
		key = true;
		socketAddress = new InetSocketAddress(ip, port );
		socket = new Socket();
		try {
			socket.connect(socketAddress, 5000);
			inputStream = socket.getInputStream();
			outputStream = socket.getOutputStream();
			mainHandler.sendEmptyMessage(Global.MY_CONNECT_SUCCESS);
			rxThread = new RxThread();
			rxThread.start();
			MonitorThread monitorThread = new MonitorThread();
			monitorThread.start();
		} catch (Exception e) {
			mainHandler.sendEmptyMessage(Global.MY_CONNECT_FAILLY);
		}
	}

	void initChildHandler() {
		Looper.prepare();
		socketHandler = new Handler() {
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case Global.SEND_MESSAGE:
					try {
						outputStream.write((byte[])msg.obj);
						outputStream.flush();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						mainHandler.sendEmptyMessage(Global.MY_RECONNECT);
					}
					break;
				case Global.DISSCONNET:
					key = false;
					try {
						inputStream.close();
						outputStream.close();
						socket.close();
						mainHandler.sendEmptyMessage(Global.MY_CONNECT_FAILLY);
					} catch (IOException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
					socketHandler.getLooper().quit();
					break;
				default:
					break;
				}
			}
		};
		Looper.loop();
	}

	public void run() {
        connect();
		initChildHandler();
	}

	public class RxThread extends Thread {
		public void run() {
			while (key) {
				try {
					 byte[] buffer = new byte[inputStream.available()];
					inputStream.read(buffer);
					if (buffer.length > 0) {
						StringBuffer read2 = new StringBuffer();
						 for (int i = 0; i < buffer.length; i++) {
							 char s = (char) buffer[i];
							 int jh = s;
							 read2.append(",0x");
							 read2.append(Integer.toHexString(jh));
					        	MainActivity.receivedata = buffer[1] & 0xFF;
					        	String hex = Integer.toHexString(buffer[i] & 0xFF);
						        if (hex.length() == 1) { 
						        	hex='0' + hex;
						        }
					        }
                        Log.e("tag", "read = "+read2);
                        Message  msg = mainHandler.obtainMessage(Global.MY_RECEIVE_MESSAGE);
                        msg.obj = buffer;
                        mainHandler.sendMessage(msg);
					}
					try {
						sleep(100);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						 mainHandler.sendEmptyMessage(Global.MY_RECONNECT);
					}
				} catch (IOException e) {
					mainHandler.sendEmptyMessage(Global.MY_RECONNECT);
				}
			}
			try {
				if (socket.isConnected())
					socket.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				mainHandler.sendEmptyMessage(Global.MY_RECONNECT);
				//e.printStackTrace();
			}
		}
	}
	public String hexString2binaryString(String hexString)  
    {  
        if (hexString == null || hexString.length() % 2 != 0)  
            return null;  
        String bString = "", tmp;  
        for (int i = 0; i < hexString.length(); i++)  
        {  
            tmp = "0000"  
                    + Integer.toBinaryString(Integer.parseInt(hexString  
                            .substring(i, i + 1), 16));  
            bString += tmp.substring(tmp.length() - 4);  
        }  
        return bString;  
    }  
	private class MonitorThread extends Thread{
		@Override
		public void run() {
			// TODO Auto-generated method stub
			boolean isMonitor = true;
			while(isMonitor){
				try{
					//byte[] datas = {0x0f,0x18};
					Message msg = socketHandler.obtainMessage(Global.SEND_MESSAGE);
					//msg.obj = datas;
					msg.obj = MainActivity.voltageSend;
					socketHandler.sendMessage(msg);
				}catch (Exception e) {
					// TODO: handle exception
					isMonitor = false;
					if(socketHandler!=null)
					socketHandler.sendEmptyMessage(Global.DISSCONNET);
				}
				try {
					sleep(30000);
				} catch (Exception e) {
					isMonitor = false;
					// TODO Auto-generated catch block
					if(socketHandler!=null)
					socketHandler.sendEmptyMessage(Global.DISSCONNET);
				}
			}
			super.run();
		}
	}
}